import Vue from 'vue'
import VueRouter from 'vue-router'
import Loginview from '../views/Loginview.vue'
import AdministratorView from '../components/AdministratorView.vue'
import store from '../store/index';
import Nprogress from 'nprogress';
import 'nprogress/nprogress.css';

// 配置NProgress
Nprogress.configure({
  easing: 'ease',  // 动画方式
  speed: 500,  // 递增进度条的速度
});

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login',

  },
  {
    path: '/login',
    name: 'login',
    component: Loginview,
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('../views/HomeView.vue'),
    children: [
      {
        path: '/home',
        name: 'MainView',
        component: () => import('../components/MainView.vue'),
      },
      {
        path:'/news/add',
        name:'newsadd',
        component:()=>import('../components/NewsAddView.vue')
      },
      {
        path: '/administrator',
        name: 'administrator',
        component: AdministratorView,
      },
      {
        path: '/news',
        name: 'news',
        component: () => import('../components/NewsView.vue'),
      },
      {
        path: '/stores',
        name: 'stores',
        component: () => import('../components/StoresView.vue'),
      },
      {
        path: '/administratorrole',
        name: 'administratorrole',
        component: () => import('../components/AdministratorroleView.vue'),
      },
      {
        path: '/house',
        name: 'house',
        component: () => import('../components/HouseView.vue'),
      },
      {
        path: '/building',
        name: 'building',
        component: () => import('../components/BuildingView.vue'), 
      },
    ],
  },
  {
    path: '/404',
    name: '404',
    component: () => import('../views/Loginview.vue'),
  },
  {
    path: '*',
    redirect: '/404',
  },
]

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err)
}
const router = new VueRouter({
  routes
})
// 在 router.beforeEach 中添加 Nprogress.start()
router.beforeEach((to, from, next) => {
  // 启动进度条
  Nprogress.start();

  let token = localStorage.getItem('token');

  // 定义"公开路由白名单"(无需 token 即可访问，如登录页、404页)
  const whiteList = ['/', '/login', '/404'];
  if (!token) {
    whiteList.includes(to.path) ? next() : next("/login");
    return;
  }

  // 已登录状态
  let isAddRouter = store.state.isAddRoute;
  if (isAddRouter) {
    next();
    return;
  }

  try {
    const asyncRouteList = store.getters.getParentMenu || [];

   const validRoutes = asyncRouteList.filter(
  (item) => item.url && item.url.trim() !== ""
);

    console.log("validRoutes", validRoutes);

    if (validRoutes.length === 0) {
      store.commit("setIsAddRoute", true)
      next(to.path === "/404" ? "/404" : "/home");
      return;
    }

    validRoutes.forEach(item => {
      let routename = item.url.trim().substring(1);
      let componentname = routename.charAt(0).toUpperCase() + routename.slice(1);
      let dynamicRoute = {
        path: item.url,
        name: routename,
        component: () => import(`@/views/${componentname}View.vue`).catch(err => {
          console.error(`加载组件 ${componentname}View 失败:`, err);
          return import('@/views/Loginview.vue');
        })
      };
      router.addRoute('home', dynamicRoute);
    });

    router.addRoute("home", {
      path: '/404',
      name: 'page404',
      component: () => import('../views/Loginview.vue'),
      meta: { hidden: true },
    });

    store.commit('setIsAddRoute', true);

    // 修复重定向逻辑
    if (to.path === '/login') {
      next({ path: '/home' });
    } else {
      // 直接跳转到目标路径，避免复杂的导航守卫状态
      next();
    }
  } catch (error) {
    console.error('动态添加路由失败:', error);
    store.dispatch("clearstate");
    next("/login");
  }
});

// 添加 afterEach 钩子来结束进度条
router.afterEach(() => {
  // 结束进度条
  Nprogress.done();
});

export default router